package com.hxx.mybatisDemo;

import com.hxx.domain.Employee;
import com.hxx.mapper.EmployeeMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestDemo {
    SqlSession sqlSession;
    @Before
    public void init(){
        System.out.println("-------Before--------");
        try {
            //读取Mybatis配置文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //基于读取Mybatis配置文件的输入流创建SqlSessionFactory对象
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
            //获取SqlSession对象
            sqlSession = build.openSession();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void test2() {
        Object o = sqlSession
                .selectOne("com.hxx.mapper.EmployeeMapper.selectEmployee", 1);
        System.out.println(o);
    }
    @Test
    public void test1() {
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        int pageNo = 2;
        int pageSize = 2;
        int currentRow = (pageNo - 1) * pageSize;
        int sizeRows = pageSize;

        Map<String, Object> map = Map.of("currentRow",currentRow,"sizeRows",sizeRows);
        mapper.selectEmployeeByMap(map).forEach(System.out::println);
    }
    @Test
    public void test3() {
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        System.out.println(mapper.countEmployee());
    }
    @Test
    public void test4() {
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee = mapper.selectEmployee(1);
        System.out.println(employee);
    }
    @Test
    public void test5() {
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        Map<String, Object> map = mapper.selectEmpNameAndMaxSalary();
        System.out.println(map);
    }
    @Test
    public void test6() {
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        List<Employee> list = mapper.selectEmployeeByMap1(1, 2);
        list.forEach(System.out::println);

    }
    @Test
    public void test7() {
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee = new Employee();
        employee.setEmpName("abc");
        employee.setEmpSalary(10000.0);
        mapper.insertEmployee(employee);
        System.out.println(employee.getEmpId());

    }

    @After
    public void close() {
        System.out.println("--------After-------");
        sqlSession.commit();
        sqlSession.close();
    }
}
